import tushare as ts
import pandas as pd
import time
import datetime

#获取全部个股复权因子

ts.set_token('883c1e2da92c0f68194fe2c4b4aa0e4da880b41ef62ff556f2da00e7')
pro = ts.pro_api()


#获取2年全部交易日
datelist = pro.trade_cal(exchange='', start_date='20170101', end_date='20190123')
datelist = datelist[datelist.is_open > 0]['cal_date']


df_data = pd.read_hdf('stock_data.h5', key='data')
df_data = df_data.swaplevel('trade_date', 'ts_code').sort_index(level = 0)
stock_list = [x[0] for x in df_data.index.values]

#循环遍历交易日
stocks_factor = pd.DataFrame()
i = 0
j = 0
for date in datelist:
    if i > 199:
        print('一分钟请求超过200，休息一分钟继续')
        time.sleep(60)
        i = 0
    else:
        print(date)
        df = pro.adj_factor(ts_code='', trade_date=date)# 获取每天个股复权因子
        stock_list1 = df['ts_code'].values.tolist()
        df.set_index(df['ts_code'],inplace=True)
        df.drop(['ts_code'], axis=1, inplace=True)

        df1 = pro.query('suspend', ts_code='', suspend_date=date, resume_date='', fields='')
        stock_list2 = df1['ts_code'].values.tolist()
        stock_list2 = list(set(stock_list2))
        for code in stock_list2:
            if code in stock_list1 :


                df.drop(code,axis = 0 ,inplace = True)
        for code in stock_list1:
            if code not in stock_list:
                j=j+1
                print(j)
                df.drop(code, axis=0, inplace=True)
        df = df.reset_index()
        stocks_factor = stocks_factor.append(df)



    i=i+1
#创建多层索引时间代码
stocks_factor = stocks_factor.set_index([stocks_factor['trade_date'], stocks_factor['ts_code']], drop=True)
stocks_factor = stocks_factor.drop(['trade_date', 'ts_code'], 1)
h5 = pd.HDFStore('stock_factor.h5', 'w', complevel=4, complib='blosc')
h5['factor'] = stocks_factor
h5.close()




